<template>
    <el-dialog
            :title="title"
            :visible.sync="isVisible"
            :width="width"
            :before-close="handleClose"
            :lock-scroll="true"
            :close-on-click-modal="false"
            custom-class="pub_dialog"
            @open="getData"
    >
        <VForm
                ref="vformComponents"
                :form="formData.form"
                :options="formData.options"
                :rules="formData.rules"
                :labelWidth="formData.labelWidth"
                :rowspan="rowspan"
                @changeAddress="changeAddress"
                @toLoadMethods="toLoadMethods"
        ></VForm>

        <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">{{openType!='detail' ? '取 消':'返 回'}}</el-button>
      <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
    </el-dialog>
</template>

<script>
    import { riskVehiclesDetail,
            riskVehiclesUpdate,
            riskVehiclesAdd } from '@/api/risk/vehicles'
    import VForm from "@/components/VForm/index";
    export default {
        components: {
            VForm,
        },
        props: {
            width: {
                type: String,
                default: "70%",
            },
            title: {
                type: String,
                default: "详情",
            },
            id:{},
            openType:{
                type:String,
                default:"add"
            },
            dialogVisible: {
                type: Boolean,
                default: false
            }
        },
        watch: {
            'width': {
                handler(newVal, oldVal) {
                    console.log('newVal===',newVal, oldVal)
                    let w = this.width.split('%')[0]
                    if(w>=60){
                        this.rowspan = 2
                    }else{
                        this.rowspan = 1
                    }
                },
                deep: true,
                immediate: true
            },
            'typeOptions':{
                handler(newVal, oldVal) {
                    this.formData.options.forEach(t=>{
                        if(t.key=='type'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },
          'dataSourceList': {
            handler(newVal, oldVal) {
              this.formData.options.forEach(t => {
                if (t.key == 'dataSourceId') {
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },
          'openType':{
            handler(newVal, oldVal) {
              // 判断是否详情，添加不可编辑标识
              this.formData.options.forEach(t=>{
                t.disabled = newVal=='detail' ? true : false
              })
            },
            deep: true,
            immediate: true
          }
        },
        computed: {
            isVisible: {
                get() {
                    return this.dialogVisible
                },
                set() {
                    this.close()
                }
            }
        },
        data() {
            return {
                rowspan:1,
                dict:{},
                formData: {
                    form: {
                            name:"",
                            type:"",
                            model:"",
                            purchaseDate:"",
                            affiliatedUnit:"",
                            affiliatedUnitAddress:"",
                            director:"",
                            directorPhone:"",
                            contacts:"",
                            contactsPhone:"",
                            communication:"",
                            preparationTime:"",
                            equipDescribe:"",
                            file:[],
                            remark:"",
                            areaCode:"",
                            mapData:null,
                            dataSource:"",
                            dataSourceId:""
                        },
                    options: [
                                   {
                                       title: "抢险车辆名称",
                                       key: "name",
                                       type: "text",
                                   },
                                {
                                    title: "车辆类型",
                                    key: "type",
                                    type: "select",
                                    multiple:false,
                                    option: {
                                        data: this.typeOptions,
                                        props: {
                                            key: "id", // 指定key对应data的字段
                                            label: "label", // 指定label对应data的字段
                                            value: "value", // 指定value对应data的字段
                                        },
                                    },
                                },
                                   {
                                       title: "品牌型号",
                                       key: "model",
                                       type: "text",
                                   },
                                   {
                                       title: "购置日期",
                                       key: "purchaseDate",
                                       type: "date",
                                   },
                                   {
                                       title: "隶属单位",
                                       key: "affiliatedUnit",
                                       type: "text",
                                   },
                                   {
                                       title: "隶属单位地址",
                                       key: "affiliatedUnitAddress",
                                       type: "text",
                                   },
                                   {
                                       title: "负责人姓名",
                                       key: "director",
                                       type: "text",
                                   },
                                   {
                                       title: "负责人电话",
                                       key: "directorPhone",
                                       type: "text",
                                   },
                                   {
                                       title: "联系人姓名",
                                       key: "contacts",
                                       type: "text",
                                   },
                                   {
                                       title: "联系人电话",
                                       key: "contactsPhone",
                                       type: "text",
                                   },
                                   {
                                       title: "应急通信方式",
                                       key: "communication",
                                       type: "text",
                                   },
                                   {
                                       title: "应急装备时间(分钟)",
                                       key: "preparationTime",
                                       type: "text",
                                   },
                                   {
                                       title: "装备描述",
                                       key: "equipDescribe",
                                       type: "text",
                                   },
                                   // {
                                   //   title: "数据来源单位",
                                   //   key: "dataSourceId",
                                   //   type: "select",
                                   //   event: "changeDataSource",
                                   //   multiple:false,
                                   //   option: {
                                   //     data: this.dataSourceList,
                                   //     props: {
                                   //       key: "id", // 指定key对应data的字段
                                   //       label: "name", // 指定label对应data的字段
                                   //       value: "id", // 指定value对应data的字段
                                   //     },
                                   //   },
                                   // },
                                   {
                                     title: "数据来源单位",
                                     key: "dataSource",
                                     type: "text",
                                   },
                                   {
                                       title: "备注",
                                       key: "remark",
                                       type: "text",
                                   },
                                   {
                                     title: "附件",
                                     key: "file",
                                     type: "file",
                                     fileType:"file",
                                     listType:"text",
                                     uploadTextTip:""
                                   },
                                {
                                  title: "行政区划",
                                  key: "areaCode",
                                  type: "gdAreaSelect",
                                },
                                {
                                  title:'地点选择',
                                  type:'mapPosition',
                                  key:'mapData',
                                },

                    ],
                    rules: {
                        name :[
                           { required: true, message: '请输入', trigger: 'blur' },
                          {max:64, message: '长度最大为64个字符', trigger: 'blur'}
                        ],
                        type :[
                        ],
                        model :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        purchaseDate :[
                        ],
                        affiliatedUnit :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        affiliatedUnitAddress :[
                          {max:64, message: '长度最大为64个字符', trigger: 'blur'}
                        ],
                        director :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        directorPhone :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        contacts :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        contactsPhone :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        communication :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        preparationTime :[
                        ],
                        equipDescribe :[
                          {max:256, message: '长度最大为256个字符', trigger: 'blur'}
                        ],
                        file :[
                        ],
                        remark :[
                          {max:256, message: '长度最大为256个字符', trigger: 'blur'}
                        ],
                        areaCode :[
                          // {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                      mapData :[
                        { required: true, message: '请设置', trigger: 'change' },
                      ],
                    },
                    labelWidth: "140px",
                },
            // 字典
                typeOptions:[],
                dataSourceList:[]
            };
        },
        methods: {
            toLoadMethods(methods) {
              this[methods]()
            },
            changeDataSource(){
              let item = this.dataSourceList.find(t=> t.id == this.formData.form.dataSourceId)
              if(undefined!=item){
                this.formData.form.dataSource = item.name
              }
            },
            initData(){
                this.formData.form.name="",
                this.formData.form.type="",
                this.formData.form.model="",
                this.formData.form.purchaseDate="",
                this.formData.form.affiliatedUnit="",
                this.formData.form.affiliatedUnitAddress="",
                this.formData.form.director="",
                this.formData.form.directorPhone="",
                this.formData.form.contacts="",
                this.formData.form.contactsPhone="",
                this.formData.form.communication="",
                this.formData.form.preparationTime="",
                this.formData.form.equipDescribe="",
                this.formData.form.file=[],
                this.formData.form.remark="",
                this.formData.form.areaCode="",
                this.formData.form.mapData=null
                this.formData.form.dataSource = ''
                this.formData.form.dataSourceId = ''
            },
          getCountySubIndex(cityCode){
            // 中山、东莞截取10位
            let filterList = ['442000000000','441900000000']
            if(filterList.findIndex(t=>t==cityCode)>-1){
              return 10;
            }
            return 6;
          },
          positionSubmitFormat(){
            let mapData = this.formData.form.mapData
            if(mapData){
              this.formData.form.lon = mapData.gpsX
              this.formData.form.lat = mapData.gpsY
              this.formData.form.address = mapData.address
              this.formData.form.areaCode = mapData.towncode
              if(mapData.towncode){
                this.formData.form.provinceCode = mapData.towncode.substr(0,2).padEnd(12,'0')
                this.formData.form.cityCode = mapData.towncode.substr(0,4).padEnd(12,'0')
                let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
                this.formData.form.countyCode = mapData.towncode.substr(0,subIndex).padEnd(12,'0')
              }
              return true
            }
            return false
          },
          positionLoadFormat(){
            let form = this.formData.form
            let mapData = {}
            if(form.address){
              mapData.address = form.address
            }
            if(form.lon) {
              mapData.gpsX = parseFloat(form.lon)
            }
            if(form.lat) {
              mapData.gpsY = parseFloat(form.lat)
            }
            if(form.areaCode && form.provinceCode && form.cityCode && form.countyCode) {
              mapData.towncode = form.areaCode
              this.formData.form.areaCode = [form.provinceCode, form.cityCode, form.countyCode]
              this.formData.form.mapData = mapData
              return
            }
            // 空置设置默认经纬度
            this.formData.form.mapData = {gpsX: 113.280637, gpsY: 23.125178}
            console.log("mpap",mapData)
          },
            submitFormat(){
                   this.formData.form.file = JSON.stringify(this.formData.form.file)
            },
            loadFormat(){
                    this.formData.form.file  = this.formData.form.file ? JSON.parse(this.formData.form.file) : []
            },
            getCheckBoxData(value,option,type){
                if(type=="submit"){
                    if(value.length==0){
                        return null
                    }
                    let temp = [];
                    value.forEach(t=>{
                        let item = option.find(x=> x.label == t)
                    if(item!=undefined){
                        temp.push(item.value)
                    }
                })
                    return temp.join(",")
                }else {
                    if(!value){
                        return []
                    }else {
                        let data = value.split(",")
                        let temp = []
                        data.forEach(t=>{
                            let item = option.find(x=> x.value == t)
                        if(item!=undefined){
                            temp.push(item.label)
                        }
                    })
                        return temp
                    }
                }
            },
            sure(){
                console.log('sure===',this.formData.form)
                this.$refs.vformComponents.$refs.form.validate().then(res=>{
                  let haveAddress = this.positionSubmitFormat()
                  if(!haveAddress){
                    this.$message.warning("请设置地址信息")
                    return
                  }
                    this.submitFormat()
                    if(this.openType == "add"){
                        this.add()
                    }else{
                        this.update()
                    }
                })
            },
            add(){
                this.formData.form.id = null
                riskVehiclesAdd(this.formData.form).then(res=>{
                    if(res.code==200){
                    this.$message({
                        message: this.$t('tips.createSuccess'),
                        type: 'success'
                    })
                    this.closeSuccess()
                    }else{
                    this.$message({
                        message: this.$t('tips.systemException'),
                        type: 'error'
                    })
                    }
                })
            },
            update(){
                   riskVehiclesUpdate(this.formData.form).then(res=>{
                        if(res.code==200){
                        this.$message({
                             message: this.$t('tips.updateSuccess'),
                            type: 'success'
                        })
                        this.closeSuccess()
                      }else{
                        this.$message({
                            message: this.$t('tips.systemException'),
                            type: 'error'
                        })
                     }
                })
            },
            cancel(){
                this.close()
            },
            handleClose(done) {
                done()
                this.close()
            },
            closeSuccess(){
                this.initData()
                this.$refs.vformComponents.$refs.form.resetFields();
                this.$emit('success')
            },
            close(){
                this.initData()
                this.$refs.vformComponents.$refs.form.resetFields();
                this.$emit('close')
            },
            changeAddress(data){
              // console.log(data)
              this.formData.form.mapData = data
              this.formData.form.areaCode = data.areaCode
            },
            getDataSourceData(){
              this.dataSourceList = [{id:"123",name:"部门1"},{id:"456",name:"部门2"}]
            },
            getData(){
              this.getDataSourceData()
              this.typeOptions = []
              this.$commonJs.filterDataDict("riskVehiclesType",this.typeOptions)
                if(this.openType!="add"){
                    riskVehiclesDetail(this.id).then(res=>{
                        if(res.code==200){
                            this.formData.form = res.data
                            this.formData.form.type = res.data.type ? parseInt(res.data.type) : res.data.type
                            this.loadFormat()
                            this.positionLoadFormat()
                         }else{
                            this.$message({
                                message: this.$t('tips.systemException'),
                                type: 'error'
                            })
                        }
                    })
                }
            }
        },
    };
</script>

<style lang="scss" scoped>

</style>
